<?php


namespace app\api\controller\order;


use app\api\controller\Api;
use app\common\audit\logic\AuditResultLogic;
use app\common\order\model\OrderAdditional;
use app\common\order\model\OrderCollect;
use app\common\order\model\OrderIncome;
use app\common\order\model\OrderProduct;
use app\common\order\validate\OrderIncomeValidate;
use app\common\order\validate\OrderProductValidate;
use app\common\order\validate\OrderValidate;
use app\common\system\model\OperateLog;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;

class Deposit extends Api
{
    // 获取定金订单
    public function detail()
    {
        $post = $this->request->post();
        if (empty($post['id'])) {
            return error([], "参数错误");
        }

        $result = [];
        $fields = "member_id,allocate_id,bridegroom,bridegroom_mobile,bride,bride_mobile,address";
        $model = new \app\common\order\model\Order();
        $order = $model->where('id', $post['id'])->field($fields)->find();
        if (empty($order)) {
            return error([], "订单不存在");
        }
        $result['order'] = $order;

        return success($result, "获取数据成功");
    }

    public function create()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        if (!isset($post['order'])) {
            return error([], "缺少order参数");
        }

        if (!isset($post['income'])) {
            return error([], "缺少income参数");
        }

        // 验证订单基本信息
        $order = $post['order'];
        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('deposit')->check($order)) {
            return error([], $orderValidate->getError());
        }

        // 验证收款信息
        $income = $post['income'];
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($income)) {
            return error([], $incomeValidate->getError());
        }

        $source = [];
        $order['order_no'] = date('YmdHis') . uniqid();
        $order['user_id'] = $user['id'];
        $model = new \app\common\order\model\Order();
        $model->startTrans();
        try {
            $model->save($order);
            $orderId = $model->id;

            $modelName = \app\common\order\model\Order::class;
            $source[$modelName] = $orderId;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 收款信息
        $income['order_id'] = $orderId;
        $income['user_id'] = $user['id'];
        $incomeModel = new OrderIncome();
        $modelName = OrderIncome::class;
        try {
            $incomeModel->save($income);
            $source[$modelName] = $incomeModel->id;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 未找到审核流程可重新发起暂存
        // if ($order['check_status'] == -1) {
        //     return success([], "暂存成功");
        // }

        $auditRsLogic = new AuditResultLogic();
        $master = $model->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'deposit'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '创建订单成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function save()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        if (!isset($post['order'])) {
            return error([], "缺少order参数");
        }

        if (!isset($post['income'])) {
            return error([], "缺少income参数");
        }

        // 验证订单基本信息
        $order = $post['order'];
        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('deposit')->check($order)) {
            return error([], $orderValidate->getError());
        }

        // 验证收款信息
        $income = $post['income'];
        $incomeValidate = new OrderIncomeValidate();
        if (!$incomeValidate->check($income)) {
            return error([], $incomeValidate->getError());
        }

        $order['user_id'] = $user['id'];
        $model = new \app\common\order\model\Order();
        $model->startTrans();
        $source = [];
        try {
            $orderRow = $model->where('id', $order['id'])->find();
            $orderRow->save($order);
            $orderId = $order['id'];

            $modelName = \app\common\order\model\Order::class;
            $source[$modelName] = $orderId;
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 收款信息
        $income['order_id'] = $orderId;
        $income['user_id'] = $user['id'];
        $incomeModel = new OrderIncome();
        $modelName = OrderIncome::class;
        try {
            $incomeRow = $incomeModel->where('id', $income['id'])->find();
            $incomeRow->save($income);
            $source[$modelName] = $income['id'];
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }

        // 未找到审核流程可重新发起暂存
        // if ($order['check_status'] == -1) {
        //     return success([], "暂存成功");
        // }

        $auditRsLogic = new AuditResultLogic();
        $master = $orderRow->getData();
        $options = [
            'company_id' => $master['company_id'],
            'timing' => 'deposit'
        ];
        try {
            $auditNo = $auditRsLogic->initAudit($master, $user, $source, $options);
            foreach ($source as $className=>$row) {
                try {
                    $where = [];
                    if (is_array($row)) {
                        $where[] = ['id', 'in', $row];
                    } else {
                        $where[] = ['id', '=', $row];
                    }
                    $class = new $className;
                    $class->where($where)->save(['check_no' => $auditNo]);
                } catch (DbException $e) {
                    return error([], $e->getMessage());
                }
            }
            $model->commit();

            return success([], '创建订单成功');
        } catch (Exception $e) {
            $msg = $e->getMessage();
        } catch (DbException $e) {
            $msg = $e->getMessage();
        }
        return error([], $msg, 404);
    }

    public function update()
    {
        $post = $this->request->post();
        $user = $this->request->user;

        $orderValidate = new OrderValidate();
        if (!$orderValidate->scene('deposit')->check($post)) {
            return error([], $orderValidate->getError());
        }

        $model = new \app\common\order\model\Order();
        $row = $model->where('id', $post['id'])->find();
        if (empty($row)) return error([], '数据已不存在');

        $model->startTrans();
        try {
            $post['user_id'] = $user['id'];
            $origin = $row->getData();
            $row->save($post);

            $changed = $row->getData();
            $modelName = \app\common\order\model\Order::class;
            OperateLog::write($user['id'], $post['id'], $origin, $changed, $modelName);
        } catch (DbException $e) {
            $model->rollback();
            return error([], $e->getMessage());
        }
        $model->commit();

        return success([], '更新成功');
    }
}